<template>
  <div style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = '';
        }),
          search_key()
      "
    ></search>

    <div class="container_main m_top10">
      <div class="p_0_10 m_top10 bg_fff">
        <div class="flex_js p_10_0">
          <div>编码列表</div>
          <div class="flex">
            <div class="flex">
              <div>当前服务企业</div>
              <el-select
                class="m_0_10"
                v-model="serviceEnterpriseId"
                @change="search_key(), get_combin_metadata_list()"
              >
                <el-option
                  v-for="item in serviceEnterpriseList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </div>
            <el-button type="primary" @click="show_code_box = true">新增</el-button>
            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable;
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true;
                  });
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e;
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="code_data_list"
          :max-height="max_height"
          highlight-current-row
          v-loading="loading"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
          ref="table2"
          border
          @row-click="
            (row) => {
              (table2_id = row.id),
                (table1_id = row.productIdentifierId),
                get_require_list();
            }
          "
        >
          <el-table-column type="index" label="序号" width="80px"></el-table-column>
          <el-table-column
            label="规格"
            prop="productSpecs"
            v-if="header_list[0].showTable"
          ></el-table-column>
          <el-table-column
            label="图号"
            prop="productNo"
            v-if="header_list[1].showTable"
          ></el-table-column>
          <el-table-column
            label="长度"
            prop="productLength"
            sortable
            v-if="header_list[2].showTable"
          >
          </el-table-column>
          <el-table-column
            label="数量"
            prop="productNum"
            sortable
            v-if="header_list[3].showTable"
          >
          </el-table-column>
          <el-table-column
            label="组号"
            prop="teamNo"
            sortable
            width="100px"
            v-if="header_list[4].showTable"
          >
          </el-table-column>
          <el-table-column
            label="模板名称"
            prop="templateName"
            sortable
            v-if="header_list[5].showTable"
          >
          </el-table-column>
          <el-table-column
            label="排序"
            prop="sort"
            sortable
            width="80px"
            v-if="header_list[6].showTable"
          >
          </el-table-column
          ><el-table-column
            label="备注"
            prop="remark"
            sortable
            width="100px"
            show-overflow-tooltip
            v-if="header_list[7].showTable"
          >
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="140px">
            <template #default="scope: any">
              <el-button @click="edit_list({ item: scope.row, type: 3 })">编辑</el-button>
              <el-button @click="edit_list({ item: scope.row, type: 4 })">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="m_10_0"
          v-model:currentPage="page_code_data.current"
          v-model:page-size="page_code_data.pageSize"
          :page-sizes="[10, 20, 500]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="code_total"
          @size-change="
            (e) => {
              page_code_data.pageSize = e;
              get_code_list();
            }
          "
          @current-change="
            (e) => {
              page_code_data.current = e;
              get_code_list();
            }
          "
        />
      </div>
      <p>=></p>
      <div>
        <div class="flex_js p_10_0">
          <div>条件列表</div>
          <el-button
            type="primary"
            @click="require_list.push(JSON.parse(JSON.stringify(require_item)))"
            >追加条件</el-button
          >
        </div>
        <el-table :data="require_list" border max-height="600">
          <el-table-column label="条件名">
            <template #default="scope">
              <el-select v-model="scope.row.productMetadataId" filterable class="m_0_5">
                <el-option
                  v-for="item in enterprise_metadata_list"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="判断方式">
            <template #default="scope">
              <el-select v-model="scope.row.subJudgmentType" filterable class="m_0_5">
                <el-option
                  v-for="item in dict_list"
                  :key="item.value"
                  :value="Number(item.value)"
                  :label="item.label"
                ></el-option>
              </el-select> </template
          ></el-table-column>
          <el-table-column label="值" width="100">
            <template #default="scope">
              <el-input
                v-model="scope.row.value"
                class="m_0_5"
                style="width: 80px"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="排序" width="100">
            <template #default="scope">
              <el-input
                v-model="scope.row.sort"
                class="m_0_5"
                style="width: 80px"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button @click="require_list.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider style="margin-top: 10px"></el-divider>
        <div class="m_top10 tr">
          <el-button type="primary" :loading="btn_loading" @click="submit_require()"
            >提交</el-button
          >
        </div>
      </div>
    </div>
    <el-drawer
      v-model="show_code_box"
      direction="rtl"
      size="50%"
      destroy-on-close
      @close="resetForm(addMetadataform)"
      :close-on-click-modal="false"
    >
      <template #title
        ><h4 v-if="add_code_form_data.id == ''">新增编码</h4>
        <h4 v-else>编辑编码</h4></template
      >
      <template #default>
        <el-form
          :model="add_code_form_data"
          :rules="rules"
          label-width="100px"
          ref="addMetadataform"
        >
          <el-form-item label="关联规格" prop="productIdentifierId">
            <el-select v-model="add_code_form_data.productIdentifierId" filterable>
              <el-option
                v-for="item in list"
                :value="item.id"
                :key="item.id"
                :label="item.productSpecs"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="长度" prop="productLength">
            <div style="width: 100%">
              <div class="flex">
                所需元数据：<el-select
                  style="flex: 1"
                  multiple
                  filterable
                  v-model="productLength_meta_list"
                  @change="select_productLength_meta_list"
                >
                  <el-option
                    v-for="item in enterprise_metadata_list"
                    :key="item.id"
                    :value="item.code"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </div>
              <div class="flex">
                <div class="fs0">长度(公式)：</div>
                <div style="overflow-x: auto; flex: 1" class="flex m_top5">
                  <div
                    v-for="item in productLength_value_list"
                    :key="item.code"
                    class="flex"
                  >
                    <span v-if="item.code != ''">{{ item.code }}</span>
                    <el-input
                      style="width: 100px"
                      v-model="item.value"
                      @input="
                        add_code_form_data.productLength = '';
                        productLength_value_list.forEach((i) => {
                          add_code_form_data.productLength += i.code + i.value;
                        });
                      "
                    ></el-input>
                  </div>
                </div>
              </div>
              <div>值：{{ add_code_form_data.productLength }}</div>
            </div>
          </el-form-item>
          <el-form-item label="数量" prop="productNum">
            <div style="width: 100%">
              <div class="flex">
                所需元数据：<el-select
                  style="flex: 1"
                  multiple
                  filterable
                  v-model="productNum_meta_list"
                  @change="select_productNum_meta_list"
                >
                  <el-option
                    v-for="item in enterprise_metadata_list"
                    :key="item.id"
                    :value="item.code"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </div>
              <div class="flex">
                <div class="fs0">数量(公式)：</div>
                <div style="overflow-x: auto; flex: 1" class="flex m_top5">
                  <div
                    v-for="item in productNum_value_list"
                    :key="item.code"
                    class="flex"
                  >
                    <span v-if="item.code != ''">{{ item.code }}</span>
                    <el-input
                      @input="
                        () => {
                          add_code_form_data.productNum = '';
                          productNum_value_list.forEach((i) => {
                            add_code_form_data.productNum += i.code + i.value;
                          });
                        }
                      "
                      style="width: 100px"
                      v-model="item.value"
                    ></el-input>
                  </div>
                </div>
              </div>
              <div>值：{{ add_code_form_data.productNum }}</div>
            </div>
          </el-form-item>
          <el-form-item label="组号" prop="teamNo">
            <el-input v-model="add_code_form_data.teamNo" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="模板名称">
            <el-input
              v-model="add_code_form_data.templateName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="add_code_form_data.sort" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="add_code_form_data.remark" placeholder="请输入"></el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addMetadataform)">取消</el-button>
            <el-button
              type="primary"
              @click="submit(addMetadataform)"
              :loading="btn_loading"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { dictData, formatDate, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import { onMounted, ref, onUnmounted, computed } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
// import { useRoute } from "vue-router";
import { FormInstance, ElMessage, ElMessageBox } from "element-plus";
// const route = useRoute();
const addMetadataform = ref<FormInstance>();
// 该页面权限组
const list = ref();
const total = ref();
const show_code_box = ref(false);
const loading = ref(false);
const height_size = ref(1);
const rules = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  productNum: [
    {
      required: true,
      message: "请输入数量",
      trigger: "blur",
    },
  ],
  productSpecs: [{ required: true, message: "请输入规格", trigger: "blur" }],
  meterWeight: [{ required: true, message: "请输入编码", trigger: "blur" }],
  productLength: [{ required: true, message: "请输入长度", trigger: "blur" }],
  teamNo: [{ required: true, message: "请输入组号", trigger: "blur" }],
  productIdentifierId: [{ required: true, message: "选择规格", trigger: "change" }],
});
const header_list = ref<any>([
  {
    label: "规格",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "图号",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "长度",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "数量",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "组号",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "模板名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "排序",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "备注",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
]);
const page_data = ref({
  current: 1,
  pageSize: 1000,
  name: "",
  productNo: "",
  productSpecs: "",
  meterWeight: "",
  isCommonUse: "",
  type: "",
  isMainProduct: "",
  sort: "",
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value;
  }),
});

const dict_list = ref();
const max_height = ref();
onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  // 根据 路由 区分
  EventBus.on("refresh", () => {
    get_code_list();
    ElMessage.success("刷新成功！");
  });
  get_serviceEnterpriseList();
  // 字典 判断方式
  dictData("1715631850325544961").then((res) => {
    dict_list.value = res as any;
    dict_list.value.forEach((item) => {
      item.label = item.dictValue;
      item.value = item.dictCode;
    });
  });
});
onUnmounted(() => {
  EventBus.off("refresh");
});
const serviceEnterpriseId = ref();
const serviceEnterpriseList = ref([]);
const get_serviceEnterpriseList = () => {
  axios.request({ url: serviceApi.serviceEnterpriseList, method: "post" }).then((res) => {
    console.log(res);
    serviceEnterpriseList.value = res.data === null ? [] : res.data;
    serviceEnterpriseId.value = res.data === null ? "" : res.data[0].id;
    console.log(serviceEnterpriseId.value);

    get_list();
    get_code_list();
    get_metadata_list();
  });
};
const btn_loading = ref(false);
const edit_list = (e) => {
  if (e.type == 3) {
    add_code_form_data.value = {
      id: e.item.id,
      productIdentifierId: e.item.productIdentifierId,
      productLength: e.item.productLength,
      productNum: e.item.productNum,
      sort: e.item.sort,
      teamNo: e.item.teamNo,
      templateName: e.item.templateName,
      remark: e.item.remark,
      serviceEnterpriseId: computed(() => {
        return serviceEnterpriseId.value;
      }),
    };
    let productNum = JSON.parse(JSON.stringify(e.item.productNum));
    let productLength = JSON.parse(JSON.stringify(e.item.productLength));
    enterprise_metadata_list.value.forEach((i) => {
      if (productNum.includes(i.code)) {
        productNum_meta_list.value.push(i.code);
        productNum = productNum.replace(i.code, ",");
      }
      if (productLength.includes(i.code)) {
        productLength_meta_list.value.push(i.code);
        productLength = productLength.replace(i.code, ",");
      }
    });
    productNum.split(",").forEach((i, index) => {
      if (index == 0) {
        productNum_value_list.value[index].value = i;
      } else {
        productNum_value_list.value.push({
          code: productNum_meta_list.value[index - 1],
          value: i,
        });
      }
    });
    productLength.split(",").forEach((i, index) => {
      if (index == 0) {
        productLength_value_list.value[index].value = i;
      } else {
        productLength_value_list.value.push({
          code: productLength_meta_list.value[index - 1],
          value: i,
        });
      }
    });
    console.log(productLength_value_list.value, productNum_value_list.value);
    show_code_box.value = true;
  } else {
    ElMessageBox.confirm("确定删除该记录？", "", {
      closeOnClickModal: false,
      type: "warning",
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.profileIdentifierCode + "/" + e.item.id,
            method: "delete",
          })
          .then(() => {
            ElMessage.success("操作成功！");
            setTimeout(() => {
              get_code_list();
            }, 1000);
          })
          .catch((err) => {
            ElMessage.error(err);
          });
      })
      .catch(() => {});
  }
};
const submit_require = () => {
  if (btn_loading.value) return;
  btn_loading.value = true;
  let data = {
    productIdentifierId: table1_id.value,
    productIdentifierCodeId: table2_id.value,
    ruleList: require_list.value,
  };
  axios
    .request({
      url: serviceApi.profileIdentifierRule,
      method: "post",
      data: data,
    })
    .then((res) => {
      console.log(res);
      ElMessage.success("操作成功！");
      setTimeout(() => {
        btn_loading.value = false;
        get_require_list();
      }, 1000);
    })
    .catch((err) => {
      ElMessage.error(err);
      btn_loading.value = false;
    });
};
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;
      axios
        .request({
          url:
            serviceApi.profileIdentifierCode +
            (add_code_form_data.value.id == "" ? "" : "/" + add_code_form_data.value.id),
          method: add_code_form_data.value.id == "" ? "post" : "put",
          data: add_code_form_data.value,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("操作成功！");
          setTimeout(() => {
            btn_loading.value = false;
            get_code_list();
            resetForm(formEl);
          }, 1000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const currentRowIndex2 = ref(0);
const table2 = ref(null);
const table1_id = ref("");
const table2_id = ref("");
const get_list = () => {
  loading.value = true;
  axios
    .request({
      url: serviceApi.profileIdentifier + "/page",
      method: "post",
      data: page_data.value,
    })
    .then((res) => {
      console.log(res);
      list.value = res.data.content;
      total.value = parseInt(res.data.totalElements);
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err);
    });
};

const productNum_meta_list = ref([]);
const productNum_value_list = ref([{ code: "", value: "" }]);
const productLength_meta_list = ref([]);
const productLength_value_list = ref([{ code: "", value: "" }]);
const select_productNum_meta_list = (e) => {
  if (e.length > productNum_value_list.value.length - 1) {
    productNum_value_list.value.push({ code: "", value: "" });
  }
  productNum_value_list.value = productNum_value_list.value.filter((i) => {
    return i.code == "" || e.includes(i.code);
  });
  add_code_form_data.value.productNum = "";
  productNum_value_list.value.forEach((i, index) => {
    if (index != 0) {
      i.code = e[index - 1];
    }
    add_code_form_data.value.productNum += i.code + i.value;
  });
};

const select_productLength_meta_list = (e) => {
  if (e.length > productLength_value_list.value.length - 1) {
    productLength_value_list.value.push({ code: "", value: "" });
  }
  productLength_value_list.value = productLength_value_list.value.filter((i) => {
    return i.code == "" || e.includes(i.code);
  });
  add_code_form_data.value.productLength = "";
  productLength_value_list.value.forEach((i, index) => {
    if (index != 0) {
      i.code = e[index - 1];
    }
    add_code_form_data.value.productLength += i.code + i.value;
  });
};
const add_code_form_data = ref({
  id: "",
  productIdentifierId: "",
  productLength: "",
  productNum: "",
  sort: "",
  teamNo: "",
  templateName: "",
  remark: "",
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value;
  }),
});
const page_code_data = ref({
  current: 1,
  pageSize: 10,
  productLength: "", // 长度
  productNum: "", // 数量
  productNo: "", // 图号
  productSpecs: "", // 规格
  teamNo: "", // 组号
  templateName: "", // 模板
  sort: "",
  reamrk: "",
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value;
  }),
});
const code_data_list = ref([]);
const code_total = ref(0);
const get_code_list = () => {
  axios
    .request({
      url: serviceApi.profileIdentifierCode + "/page",
      method: "post",
      data: handle_search_key(page_code_data.value),
    })
    .then((res) => {
      console.log(res);
      if (res.data.content.length) {
        table2.value.setCurrentRow(res.data.content[currentRowIndex2.value]);
        table2_id.value = res.data.content[currentRowIndex2.value].id;
        table1_id.value = res.data.content[currentRowIndex2.value].productIdentifierId;
        get_require_list();
      }
      code_data_list.value = res.data.content;
      code_total.value = parseInt(res.data.totalElements);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const require_list = ref([]);
const require_item = ref({
  productMetadataId: "",
  sort: "",
  subJudgmentType: "",
  value: "",
});
const get_require_list = () => {
  axios
    .request({
      url: serviceApi.profileIdentifierRule + "/page",
      method: "post",
      data: {
        current: 1,
        pageSize: 1000,
        productIdentifierId: table1_id.value,
        productIdentifierCodeId: table2_id.value,
      },
    })
    .then((res) => {
      console.log(res);
      require_list.value = res.data.content;
      require_item.value.sort = (Number(res.data.totalElements) + 1) as any;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const metadata_list = ref([]);
const get_metadata_list = () => {
  axios
    .request({
      url: serviceApi.profileMetadata,
      method: "post",
      data: {},
    })
    .then((res) => {
      console.log(res);
      metadata_list.value = res.data;
      get_combin_metadata_list();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const enterprise_metadata_list = ref([]);
const combin_metadata_list_page_data = ref({
  current: 1,
  pageSize: 1000,
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value;
  }),
});
const get_combin_metadata_list = () => {
  axios
    .request({
      url: serviceApi.MetadataCombine + "/page",
      method: "post",
      data: combin_metadata_list_page_data.value,
    })
    .then((res) => {
      console.log(res);
      res.data.content.forEach((i) => {
        i.name += "(组合)";
      });
      enterprise_metadata_list.value = metadata_list.value.concat(
        res.data.content.filter((i) => {
          return i.status;
        })
      );
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_code_form_data.value.id = "";
  //   add_code_form_data.value = {
  //     id: "",
  //     productIdentifierId: "",
  //     productLength: "",
  //     productNum: "",
  //     sort: "",
  //     teamNo: "",
  //     templateName: "",
  //     remark: "",
  //     serviceEnterpriseId: computed(() => {
  //       return serviceEnterpriseId.value;
  //     }),
  //   };
  //   productNum_meta_list.value = [];
  //   productNum_value_list.value = [{ code: "", value: "" }];
  //   productLength_meta_list.value = [];
  //   productLength_value_list.value = [{ code: "", value: "" }];
  show_code_box.value = false;
};
const search_key = () => {
  page_code_data.value = {
    current: 1,
    pageSize: 10,
    productLength: header_list.value[2].value, // 长度
    productNum: header_list.value[3].value, // 数量
    productNo: header_list.value[1].value, // 图号
    productSpecs: header_list.value[0].value, // 规格
    teamNo: header_list.value[4].value, // 组号
    templateName: header_list.value[5].value, // 模板
    sort: header_list.value[6].value,
    reamrk: header_list.value[7].value,
    serviceEnterpriseId: computed(() => {
      return serviceEnterpriseId.value;
    }),
  };
  get_code_list();
};
</script>

<style lang="scss" scoped>
.container_main {
  display: flex;
  align-items: center;
  background-color: #fff;
  height: calc(100% - 80px);
  > div:first-child {
    width: 58%;
    height: 100%;
  }
  > div:last-child {
    height: 100%;
    width: 40%;
  }
}
.top_title {
  display: flex;
  align-items: center;
  padding: 2px 5px;
  border: 1px solid #666;
  border-radius: 10px;
  color: #666;
  cursor: pointer;
  &:hover {
    border-color: #3580eb;
    color: #3580eb;
  }
}
.select_me {
  transform: rotate(90deg);
}
</style>
